package com.example.mybatisdemo.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author scc
 * @since 2022/8/9 10:40
 */
@Configuration
public class DataSourceConfiguration {


    @Autowired
    private DynamicDataSourceInterceptor dataSourceInterceptor;


    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.addInterceptor(dataSourceInterceptor);
            }
        };
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.linkage")
    public DataSource linkageDataSource(){
        return DruidDataSourceBuilder.create().build();
    }


    @Bean
    @ConfigurationProperties("spring.datasource.druid.gov")
    public DataSource govDataSource(){
        return DruidDataSourceBuilder.create().build();
    }


//    @Bean
//    @ConfigurationProperties("spring.datasource.druid.sugetong")
//    public DataSource sugetongDataSource(){
//        return DruidDataSourceBuilder.create().build();
//    }

    @Bean
    @Primary
    public DynamicDataSource dataSource() {
        Map<String, DataSource> targetDataSources = new HashMap<>();
        targetDataSources.put(DynamicDataSourceHolder.master, masterDataSource());
        targetDataSources.put(DynamicDataSourceHolder.linkage, linkageDataSource());
        targetDataSources.put(DynamicDataSourceHolder.gov, govDataSource());
//        targetDataSources.put(DynamicDataSourceHolder.sugetong, sugetongDataSource());


        return new DynamicDataSource(masterDataSource(), targetDataSources);
    }

}
